package com.study.limiter;


import com.google.common.io.Files;
import com.study.locks.redis.JedisPoolUtil;
import org.springframework.core.io.ClassPathResource;
import redis.clients.jedis.Jedis;

import java.nio.charset.Charset;

/**
 * @author: chenhs
 * @date: Created in 6:30 2019/12/26
 **/
public class JedisLuaTimeWindowLimiter {

    private String luaScript;

    private String key;

    private String limit;

    private String expire;

    public JedisLuaTimeWindowLimiter(String key, String limit, String expire, String scriptFile) {
        this.key = key;
        this.limit = limit;
        this.expire = expire;

        try {
            luaScript = Files.asCharSource(new ClassPathResource(scriptFile).getFile(), Charset.forName("UTF-8")).read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean acqure() {
        Jedis jedis = null;
        try {
            jedis = JedisPoolUtil.getJedis();
            return (Long) jedis.eval(luaScript, 1, key, limit, expire) == 1L;
        } finally {
            // 这里用完一定要关闭
            JedisPoolUtil.closeJedis(jedis);
        }
    }

}
